<template>
    <el-card class="group-buy-card">
        <template #header>
            <div class="card-header">
                <!-- 调整元素顺序 -->
                <div class="header-left">
                    <span class="title">
                        <img width="32" height="32" src="/images/edu/group-buy.png">
                        今日团购
                    </span>
                    <el-tag type="danger" effect="dark" size="small">限时特惠</el-tag>
                     <!--倒计时 start -->
                <div class="enhanced-countdown">
                    <div class="countdown-label">
                        <el-icon>
                            <Clock />
                        </el-icon>
                        <span>截团倒计时</span>
                    </div>
                    <el-countdown :value="groupEndTime" class="digital-clock" :format="formatTime">
                        <!-- 使用title插槽承载主要内容 -->
                        <template #title>
                            <div class="time-blocks">
                                <div class="time-block">
                                    <span class="number">{{ padZero(timeData.hours) }}</span>
                                    <span class="unit">时</span>
                                </div>
                                <div class="colon">:</div>
                                <div class="time-block">
                                    <span class="number">{{ padZero(timeData.minutes) }}</span>
                                    <span class="unit">分</span>
                                </div>
                                <div class="colon">:</div>
                                <div class="time-block">
                                    <span class="number">{{ padZero(timeData.seconds) }}</span>
                                    <span class="unit">秒</span>
                                </div>
                            </div>
                        </template>
                    </el-countdown>
                </div>
                <!--  倒计时 end -->
                </div>

                <!--查看更多 start-->
                <div class="header-right">
                    
                <el-button 
                    type="danger" 
                    plain 
                    size="small"
                    @click="$router.push('/groupBuyList')"
                >
                    查看更多团购 >
                </el-button>
                </div>
                <!-- 查看更多 end -->

               

            </div>
        </template>

        <el-row :gutter="20">
            <el-col v-for="(item, index) in groupItems" :key="index" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                <div class="group-item">
                    <div class="cover-wrapper">
                        <el-image :src="item.cover" class="group-cover" fit="cover" />
                        <el-tag v-if="item.isHot" type="danger" effect="dark" class="hot-tag">
                            <el-icon>
                                <MagicStick />
                            </el-icon>
                            爆款推荐
                        </el-tag>
                    </div>

                    <div class="group-info">
                        <h4 class="title">{{ item.title }}</h4>
                        <p class="teacher">讲师：{{ item.teacher }}</p>

                        <div class="price-section">
                            <div class="price-group">
                                <span class="group-price">¥{{ item.groupPrice }}</span>
                                <del class="original-price">¥{{ item.originalPrice }}</del>
                                <span class="discount-rate">{{ item.discount }}折</span>
                            </div>

                            <div class="meta-info">
                                <el-progress :percentage="item.soldPercent" :color="customColors" :show-text="false" />
                                <div class="stock-info">
                                    <span>已参团{{ item.sold }}/{{ item.total }}</span>
                                    <span>剩余{{ item.remaining }}名额</span>
                                </div>
                            </div>
                        </div>

                        <el-button type="danger" size="small" class="group-btn" @click.stop="joinGroup(item.id)">
                            <el-icon>
                                <ShoppingCart />
                            </el-icon>
                            立即参团
                        </el-button>
                    </div>
                </div>
            </el-col>
        </el-row>
    </el-card>
</template>
  
<script setup lang="ts">
import { ShoppingCart, MagicStick } from '@element-plus/icons-vue'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { joinGroupBuyApi } from '@/api';

const props = defineProps({
    groupItems: {
        type: Array,
        required: true
    },
    loading: {
        type: Boolean,
        default: true
    }
})

// 示例倒计时时间（当天23:59:59）
const groupEndTime = new Date(new Date().setHours(23, 59, 59, 999))
const timeData = ref({ hours: 0, minutes: 0, seconds: 0 })
const padZero = (num: number) => num.toString().padStart(2, '0')


// 计算剩余时间
const updateTime = () => {
    const remaining = Math.max(0, groupEndTime - Date.now())
    timeData.value = {
        hours: Math.floor(remaining / (1000 * 60 * 60)),
        minutes: Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60)),
        seconds: Math.floor((remaining % (1000 * 60)) / 1000)
    }
}
const formatTimes = ({ hours, minutes, seconds }) =>
    `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`

    // 参加团购
const joinGroup = async(id: number) => {
    console.log('参加团购:', id)
    try {
        const {code,msg,data} = await joinGroupBuyApi(id)
        if(code === 1){
            const divForm = document.getElementById("alpayDiv");
            if (divForm)divForm.remove()
            const div = document.createElement("div");
            div.setAttribute("id", "alpayDiv");
            div.innerHTML = data ; // data就是接口返回的form 表单字符串
            document.body.appendChild(div);
            // 新开窗口跳转
            document.forms[0].setAttribute("target", "_blank");
            document.forms[0].submit();
        }else{
            ElMessage.error(msg)
        }
    } catch (error) {
        
    }
}

// 进度条渐变色
const customColors = [
    { color: '#f56c6c', percentage: 20 },
    { color: '#e6a23c', percentage: 40 },
    { color: '#5cb87a', percentage: 60 },
    { color: '#1989fa', percentage: 80 },
    { color: '#6f7ad3', percentage: 100 }
]
// 初始化定时器
let timer: number
onMounted(() => {
    updateTime()
    timer = window.setInterval(updateTime, 1000)
})

onBeforeUnmount(() => {
    clearInterval(timer)
})

</script>
  
<style lang="scss" scoped>
.group-buy-card {
    margin-bottom: 20px;
    border-radius: 12px;

    :deep(.el-card__header) {
        padding: 12px 20px;
        background: linear-gradient(135deg, #fff6f6 0%, #ffeceb 100%);

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .header-left {
                display: flex;
                align-items: center;
                gap: 12px;

            }

            .header-right {
                margin-left: auto;
                padding-left: 20px;
            }


        
        }

    }

    .card-header {
        font-size: 18px;
        font-weight: 600;
        color: #303133;

        img {
            vertical-align: middle;
            margin-right: 8px;
        }
    }

    .group-item {
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s ease;
        cursor: pointer;

        &:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .cover-wrapper {
            position: relative;
            height: 180px;

            .hot-tag {
                position: absolute;
                top: 12px;
                left: -30px;
                padding: 8px 32px;
                transform: rotate(-45deg);
                font-weight: bold;
                border-radius: 0;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

                .el-icon {
                    vertical-align: -2px;
                    margin-right: 4px;
                }
            }
        }

        .group-cover {
            width: 100%;
            height: 100%;
            border-radius: 8px 8px 0 0;
        }

        .group-info {
            padding: 16px;

            .title {
                font-size: 16px;
                color: #303133;
                margin-bottom: 8px;
            }

            .teacher {
                font-size: 12px;
                color: #909399;
                margin-bottom: 12px;
            }

            .price-section {
                margin: 16px 0;

                .price-group {
                    display: flex;
                    align-items: baseline;
                    gap: 8px;
                    margin-bottom: 12px;

                    .group-price {
                        color: #f56c6c;
                        font-size: 24px;
                        font-weight: 700;
                    }

                    .original-price {
                        color: #909399;
                        font-size: 14px;
                    }

                    .discount-rate {
                        color: #fff;
                        background: #f56c6c;
                        padding: 2px 8px;
                        border-radius: 4px;
                        font-size: 12px;
                    }
                }

                .meta-info {
                    .el-progress {
                        margin-bottom: 8px;
                    }

                    .stock-info {
                        display: flex;
                        justify-content: space-between;
                        font-size: 12px;
                        color: #606266;
                    }
                }
            }

            .group-btn {
                width: 100%;
                font-weight: bold;
                letter-spacing: 1px;

                .el-icon {
                    margin-right: 6px;
                }
            }
        }
    }
}

// 右边倒计时样式
.enhanced-countdown {
    display: flex;
    align-items: center;
    gap: 12px;
    background: rgba(245, 108, 108, 0.08);
    padding: 8px 16px;
    border-radius: 8px;
    border: 1px solid rgba(245, 108, 108, 0.2);
    
    /* 隐藏原生倒计时内容 */
    :deep(.el-statistic__content) {
        display: none; 
    }
    .countdown-label {
        display: flex;
        align-items: center;
        gap: 6px;
        color: #f56c6c;
        font-size: 14px;

        .el-icon {
            font-size: 16px;
            animation: pulse 1.5s infinite;
        }
    }

    .digital-clock {
        .time-blocks {
            display: flex;
            align-items: center;
            gap: 8px;

            .time-block {
                display: flex;
                flex-direction: column;
                align-items: center;
                background: rgba(245,108,108,0.1);
                padding: 4px 8px;
                border-radius: 4px;

                .number {
                    font-size: 18px;
                    font-weight: bold;
                    color: #f56c6c;
                    font-family: monospace;
                }

                .unit {
                    font-size: 12px;
                    color: #f56c6c;
                    transform: scale(0.9);
                }
            }

            .colon {
                color: #f56c6c;
                font-weight: bold;
                margin: 0 2px;
            }
        }
    }
}

@keyframes pulse {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }

    100% {
        opacity: 1;
    }
}
</style>